package de.koller.kelvin.engine;

import de.koller.kelvin.KNode;
import de.koller.kelvin.engine.landscape.LandscapeDisplay;
import de.koller.kelvin.engine.landscape.LandscapeGenerator;
import de.koller.kelvin.engine.landscape.LandscapeTile;
import de.koller.oceanFramework.tree.Child;
import java.awt.Graphics2D;
import java.util.ArrayList;

public class TileMap extends KNode {
	
	public static final int TILE_SIZE = 100;
	
	@Child public final LandscapeGenerator landscapeGenerator = new LandscapeGenerator();
	
	private int tileOffsetX = -1, tileOffsetY = -1;
	private final LandscapeTile[][] tiles = new LandscapeTile[10][8];

	@Override
	protected void update( int elapsedTime ) {
		super.update( elapsedTime );
		
		int ox = (int)Math.floor( kroot.render.camera.position.x / TILE_SIZE );
		int oy = (int)Math.floor( kroot.render.camera.position.y / TILE_SIZE );
		
		if( !( ox == tileOffsetX && oy == tileOffsetY ) )
			recalcTiles( ox, oy );
	}
	
	private void recalcTiles( int ox, int oy ) {
		tileOffsetX = ox;
		tileOffsetY = oy;
		
		ArrayList<LandscapeTile> lt = new ArrayList<>();
		for( int x = 0; x < tiles.length; x++ )
			for( int y = 0; y < tiles[0].length; y++ )
				if( tiles[x][y] != null )
					lt.add( tiles[x][y] );
		
		for( int x = 0; x < tiles.length; x++ )
			for( int y = 0; y < tiles[0].length; y++ ) {
				int tx = tileOffsetX + x;
				int ty = tileOffsetY + y;
				
				LandscapeTile mt = null;
				for( LandscapeTile t : lt )
					if( t.tx == tx && t.ty == ty ) {
						mt = t;
						break;
					}
				
				if( mt == null )
					mt = new LandscapeTile( landscapeGenerator, tx, ty );
				
				tiles[x][y] = mt;
			}
				
	}
	
	public void render( Graphics2D g ) {
		for( int tx = 0; tx < tiles.length; tx++ )
			for( int ty = 0; ty < tiles[0].length; ty++ ) {
				LandscapeTile t = tiles[tx][ty];
				int x = tileOffsetX * TILE_SIZE + tx * TILE_SIZE;
				int y = tileOffsetY * TILE_SIZE + ty * TILE_SIZE;
					
				if( t != null )
					t.render( g, x, y, LandscapeDisplay.Surface );
			}
	}
	
}
